import React, { useReducer } from 'react';

//添加init函数作为useReducer的第三个参数。
function init(initialCount){
    return {count:initialCount};
}

function reducer(state,action){
    switch(action.type){
        case 'increment':
            return {count: state.count + 1}; 
        case 'decrement':
            return {count: state.count - 1};
        case "reset":
            //在此调用init函数，通过dispatch的payload传入值。
            return init(action.payload);
        default:
            return new Error();
    }
}

export default({initialCount=0})=>{
    const [state,dispatch]=useReducer(reducer,initialCount,init);
    
    return(
        <>
            <br/>
            Count:{state.count}
            <br/>
            <button
                onClick={() => dispatch({type: 'reset', payload: initialCount})}>
                Reset
            </button>
            <button onClick={() => dispatch({type: 'increment'})}>+</button>
            <button onClick={() => dispatch({type: 'decrement'})}>-</button>
            {/* 如果点击一次按钮能够连续加两次，则说明reducer是 同步 更新数据 */}
            <button onClick={() => {
                dispatch({type: 'increment'});
                dispatch({type: 'increment'});
            }}>
                测试能否连续加两次
            </button>
        </>
    )
}
